/**
* Copyright: Copyright (c) 2015 BlackFalcon
* 
* @ClassName: AccessTokenRefreshSchedule.java
* @Description: 
*
* @version: v1.0.0
* @author: Administrator
* @date: 11:18:26 AM 
*
* Modification History:
* Date         Author          Version            Description
*---------------------------------------------------------*
* Jun 9, 2015     Administrator           v1.0.0
*/

package com.fengke.schedule.tencent;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;

import com.fengke.dao.model.SystemParam;
import com.fengke.payment.tencent.common.Configure;
import com.fengke.payment.tencent.common.RestHttpRequestHelper;
import com.fengke.service.SystemParamService;
import com.fengke.util.Constants;
import com.fengke.util.LoggerFactory;
import com.fengke.util.StringUtil;

/**
 * 每两个小时刷新微信AccessToken
 * 并刷新jsapi_ticket
 *
 */
public class AccessTokenRefreshSchedule {
	private Logger logger = LoggerFactory.getLogger(AccessTokenRefreshSchedule.class);
	private SystemParamService systemParamService;
	public void refresh() {
		// 获取参数，判断是否过期
		SystemParam accessToken = new SystemParam();
		accessToken.setType(SystemParam.ParamType.access_token);
		try {
			accessToken = systemParamService.researchSystemParamByType(accessToken);
		} catch (Exception e) {
			logger.error("researchSystemParamByType Exception !accessToken=" + accessToken, e);
		}
		
		SystemParam jsapiTicket = new SystemParam();
		jsapiTicket.setType(SystemParam.ParamType.jsapi_ticket);
		try {
			jsapiTicket = systemParamService.researchSystemParamByType(jsapiTicket);
		} catch (Exception e) {
			logger.error("researchSystemParamByType Exception !jsapiTicket=" + jsapiTicket, e);
		}
		
		Calendar now = Calendar.getInstance();
		now.add(Calendar.HOUR, -2);
		if(accessToken.getModifyDate().after(now.getTime()) && jsapiTicket.getModifyDate().after(now.getTime())) {
			logger.info("access_ticket未过期，无需更新！accessToken=" + accessToken + ",jsapiTicket=" + jsapiTicket);
			return;
		}
		
		// 重新获取
		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("grant_type", "client_credential");
		paramMap.put("appid", Configure.getAppid());
		paramMap.put("secret", Configure.getAppSecret());
		String returnStr = RestHttpRequestHelper.executeHttpRequest(Configure.URL_ACCESS_TOKEN, paramMap);
		Map<String,String> map = new HashMap<String,String>();
		ObjectMapper mapper = new ObjectMapper();
		try {
			map = mapper.readValue(returnStr, new TypeReference<HashMap<String,String>>(){});
		} catch (JsonParseException e) {
			logger.error("access_token return json exchange Exception !returnStr=" + returnStr, e);
		} catch (JsonMappingException e) {
			logger.error("access_token return json exchange Exception !returnStr=" + returnStr, e);
		} catch (IOException e) {
			logger.error("access_token return json exchange Exception !returnStr=" + returnStr, e);
		}
		logger.info("重新获取access_token，微信返回结果为：" + returnStr);
		String access_token = map.get(Constants.WeiXinParam.ACCESS_TOKEN_RETURN);
		if(StringUtil.isEmpty(access_token)) {
			logger.error("重新获取access_token失败！");
			return;
		}
		// 获取jsapi_ticket
		paramMap = new HashMap<String, String>();
		paramMap.put("type", "jsapi");
		paramMap.put(Constants.WeiXinParam.ACCESS_TOKEN_PARAM, access_token);
		returnStr = RestHttpRequestHelper.executeHttpRequest(Configure.URL_JSAPI_TICKET, paramMap);
		logger.info("重新获取jsapi_ticket，微信返回结果为：" + returnStr);
		try {
			map = mapper.readValue(returnStr, new TypeReference<HashMap<String,String>>(){});
		} catch (JsonParseException e) {
			logger.error("jsapi_ticket return json exchange Exception !returnStr=" + returnStr, e);
		} catch (JsonMappingException e) {
			logger.error("jsapi_ticket return json exchange Exception !returnStr=" + returnStr, e);
		} catch (IOException e) {
			logger.error("jsapi_ticket return json exchange Exception !returnStr=" + returnStr, e);
		}
		String ticket = map.get(Constants.WeiXinParam.JSAPI_TICKET_RETURN);
		if(StringUtil.isEmpty(ticket)) {
			logger.error("重新获取jsapi_ticket失败！");
			return;
		}
		// 更新数据库信息
		accessToken.setParamValue(access_token);
		accessToken.setModifyDate(new Date());
		jsapiTicket.setParamValue(ticket);
		jsapiTicket.setModifyDate(new Date());
		
		try {
			systemParamService.updateSystemParamByType(accessToken);
		} catch (Exception e) {
			logger.error("updateSystemParamByType Exception !accessToken=" + accessToken, e);
		}
		try {
			systemParamService.updateSystemParamByType(jsapiTicket);
		} catch (Exception e) {
			logger.error("updateSystemParamByType Exception !jsapiTicket=" + jsapiTicket, e);
		}
	}
	
	public SystemParamService getSystemParamService() {
		return systemParamService;
	}
	public void setSystemParamService(SystemParamService systemParamService) {
		this.systemParamService = systemParamService;
	}
	/**
	 * 测试方法
	 * @param args
	 */
	public static void main(String[] args) {
		//new AccessTokenRefreshSchedule().refresh();
		Calendar now = Calendar.getInstance();
		System.out.println(now.getTime());
		System.out.println(now.getTime().after(new Date()));
		now.add(Calendar.HOUR, -2);
		System.out.println(now.getTime());
		System.out.println(now.getTime().after(new Date()));
	}
}
